<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="博客标题" prop="title">
          <el-input
            v-model="queryParams.title"
            placeholder="博客标题"
            clearable
            style="width: 200px"
            @keyup.enter="handleQuery()"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select
            v-model="queryParams.status"
            placeholder="请选择状态"
            clearable
            style="width: 150px"
          >
            <el-option label="草稿" :value="0" />
            <el-option label="发布" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon>
              <Search />
            </template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon>
              <Refresh />
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never">
      <div class="mb-10px">
        <el-button v-hasPerm="['chat:mrt-blog:add']" type="success" @click="handleOpenDialog()">
          <template #icon>
            <Plus />
          </template>
          新增
        </el-button>
        <el-button
          v-hasPerm="['chat:mrt-blog:delete']"
          type="danger"
          :disabled="removeIds.length === 0"
          @click="handleDelete()"
        >
          <template #icon>
            <Delete />
          </template>
          删除
        </el-button>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="pageData"
        highlight-current-row
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column key="title" label="博客标题" prop="title" min-width="150" align="center" />
        <el-table-column key="author" label="作者" prop="author" min-width="150" align="center" />
        <el-table-column key="slug" label="博客别名" prop="slug" min-width="150" align="center" />
        <el-table-column key="tags" label="标签" prop="tags" min-width="150" align="center" />
        <el-table-column
          key="coverImage"
          label="封面图"
          prop="coverImage"
          min-width="150"
          align="center"
        >
          <template #default="scope">
            <ImageDisplay :images="scope.row.coverImage" height="30px" />
          </template>
        </el-table-column>
        <el-table-column key="status" label="状态" prop="status" min-width="150" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'warning'">
              {{ scope.row.status === 1 ? "发布" : "草稿" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="isTop" label="是否置顶" prop="isTop" min-width="150" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isTop === 1 ? 'success' : 'info'">
              {{ scope.row.isTop === 1 ? "是" : "否" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column key="regin" label="地区" prop="regin" min-width="150" align="center" />
        <el-table-column
          key="createTime"
          label="创建时间"
          prop="createTime"
          min-width="150"
          align="center"
        />
        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-hasPerm="['chat:mrt-blog:edit']"
              type="primary"
              size="small"
              link
              @click="handleOpenDialog(scope.row.id)"
            >
              <template #icon>
                <Edit />
              </template>
              编辑
            </el-button>
            <el-button
              v-hasPerm="['chat:mrt-blog:delete']"
              type="danger"
              size="small"
              link
              @click="handleDelete(scope.row.id)"
            >
              <template #icon>
                <Delete />
              </template>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery()"
      />
    </el-card>

    <!-- 博客表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="1000px"
      class="form-dialog"
      @close="handleCloseDialog"
    >
      <el-form ref="dataFormRef" :model="formData" :rules="rules" label-width="120px">
        <el-form-item label="博客标题" prop="title">
          <el-input v-model="formData.title" placeholder="博客标题" />
        </el-form-item>

        <el-form-item label="作者" prop="author">
          <el-input v-model="formData.author" placeholder="作者" />
        </el-form-item>

        <el-form-item label="博客别名" prop="slug">
          <el-input
            v-model="formData.slug"
            placeholder="博客别名（URL标识，唯一不可重复）"
            @input="handleSlugInput"
          />
        </el-form-item>

        <el-form-item label="标签" prop="tags">
          <el-input v-model="formData.tags" placeholder="标签（英文逗号分隔）" />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="封面图" prop="coverImage">
          <SingleImageUpload v-model="formData.coverImage" />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="正文内容" prop="content">
          <WangEditor v-model="formData.content" height="500px" />
        </el-form-item>

        <el-form-item v-if="dialog.visible" label="博客视频" prop="videos">
          <MultiImageUpload
            v-model="formData.videos"
            type="video"
            accept="video/*"
            :maxFileSize="150"
            :limit="3"
          />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="草稿" :value="0" />
            <el-option label="发布" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="是否置顶" prop="isTop">
          <el-select v-model="formData.isTop" placeholder="请选择是否置顶">
            <el-option label="否" :value="0" />
            <el-option label="是" :value="1" />
          </el-select>
        </el-form-item>

        <el-form-item label="地区" prop="regin">
          <el-input v-model="formData.regin" type="textarea" placeholder="多个使用英文逗号分隔" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit()">确定</el-button>
          <el-button @click="handleCloseDialog()">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import MrtBlogAPI from "@/api/mrt/mrt-blog.js";
import SingleImageUpload from "@/components/Upload/SingleImageUpload.vue";
import MultiImageUpload from "@/components/Upload/MultiImageUpload.vue";
import WangEditor from "@/components/WangEditor/index.vue";

defineOptions({
  name: "MrtBlog",
  inheritAttrs: false,
});

const queryFormRef = ref();
const dataFormRef = ref();

const loading = ref(false);
const removeIds = ref([]);
const total = ref(0);

const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
});

// 博客表格数据
const pageData = ref([]);

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
});

// 博客表单数据
const formData = reactive({});

// 博客表单校验规则
const rules = reactive({
  title: [{ required: true, message: "请输入博客标题", trigger: "blur" }],
  author: [{ required: true, message: "请输入作者", trigger: "blur" }],
  status: [{ required: true, message: "请选择状态", trigger: "blur" }],
  isTop: [{ required: true, message: "请选择是否置顶", trigger: "blur" }],
  slug: [{ required: true, message: "请输入博客别名", trigger: "blur" }],
  coverImage: [{ required: true, message: "请选择封面图", trigger: "blur" }],
  content: [{ required: true, message: "请输入正文内容", trigger: "blur" }],
});

/** 查询博客 */
function handleQuery() {
  loading.value = true;
  MrtBlogAPI.getPage(queryParams)
    .then((data) => {
      pageData.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 处理别名输入，只允许字母、数字、连字符和下划线，空格替换为连字符，首字母小写 */
function handleSlugInput(value) {
  // 将空格替换为连字符
  let cleanValue = value.replace(/\s+/g, "-");
  // 移除除字母、数字、连字符和下划线以外的字符
  cleanValue = cleanValue.replace(/[^a-zA-Z0-9\-_]/g, "");
  // 首字母转为小写
  if (cleanValue.length > 0) {
    cleanValue = cleanValue.charAt(0).toLowerCase() + cleanValue.slice(1);
  }
  formData.slug = cleanValue;
}

/** 重置博客查询 */
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  handleQuery();
}

/** 行复选框选中记录选中ID集合 */
function handleSelectionChange(selection) {
  removeIds.value = selection.map((item) => item.id);
}

/** 打开博客弹窗 */
function handleOpenDialog(id) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改博客";
    MrtBlogAPI.getFormData(id).then((data) => {
      Object.assign(formData, data);
    });
  } else {
    dialog.title = "新增博客";
  }
}

/** 提交博客表单 */
function handleSubmit() {
  dataFormRef.value.validate((valid) => {
    if (valid) {
      loading.value = true;
      const id = formData.id;
      if (id) {
        MrtBlogAPI.update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        MrtBlogAPI.add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭博客弹窗 */
function handleCloseDialog() {
  dialog.visible = false;
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();
  Object.keys(formData).forEach((key) => {
    formData[key] = undefined;
  });
}

/** 删除博客 */
function handleDelete(id) {
  const ids = [id || removeIds.value].join(",");
  if (!ids) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      MrtBlogAPI.deleteByIds(ids)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

onMounted(() => {
  handleQuery();
});
</script>
